//
//  TeacherDetailController.swift
//  BodyBuilding
//
//  Created by franze on 2017/10/3.
//  Copyright © 2017年 franze. All rights reserved.
//

import UIKit
var chatArray:Array<NSDictionary>?

class TeacherDetailController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    var infoDict:NSDictionary!
    var videoPlayer:VideoPlayer!
    var hideState = false
    var mainScrollView:UIScrollView!
    var btnView:YButtonView!
    var field:UITextField!
    var tableView:UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        viewConfig()
    }
    
    func viewConfig(){
        view.backgroundColor = UIColor.white
        
        let navBar = CustomNavBar(frame: CGRect(origin: .zero, size: CGSize(width: WIDTH, height: 64)))
        navBar.initialize(text: "大师")
        view.addSubview(navBar)
        
        let imageView = UIImageView()
        imageView.sd_setImage(with: URL(string: BB_IMAGEURLPRE+(infoDict.value(forKey: "thumb") as! String)), placeholderImage: UIImage(named:"placeholder"))
        imageView.frame = CGRect(x: 0, y: 64, width: WIDTH, height: (HEIGHT-69)/3)
        view.addSubview(imageView)
        
        btnView = YButtonView(frame: CGRect(x: 0, y: 75+imageView.bounds.height, width: WIDTH, height: 54))
        btnView.initialize(titles: ["视频","提问"])
        btnView.backgroundColor = UIColor.white
        view.addSubview(btnView)
        
        mainScrollView = UIScrollView(frame: CGRect(x: 0, y: btnView.frame.origin.y+56, width: WIDTH, height: HEIGHT-64))
        mainScrollView.contentSize = CGSize(width: WIDTH*2, height: 0)
        mainScrollView.contentInsetAdjustmentBehavior = .never
        mainScrollView.backgroundColor = view.backgroundColor
        mainScrollView.isScrollEnabled = false
        mainScrollView.layer.masksToBounds = false
        view.addSubview(mainScrollView)
        
        videoPlayer = VideoPlayer(frame: CGRect(x: 0, y: 10, width: WIDTH, height: 200))
        videoPlayer.initialize(itemUrl:BB_VIDEOURL)
        mainScrollView.addSubview(videoPlayer)
        
        let lessonLabel = UILabel(frame: CGRect(x: 15, y: videoPlayer.bounds.height+20, width: 270, height: 20))
        lessonLabel.font = UIFont.systemFont(ofSize: 16)
        lessonLabel.text = "教授课程: \(infoDict.value(forKey: "actcate_name") as! String)"
        mainScrollView.addSubview(lessonLabel)
        
        let clubLabel = UILabel(frame: CGRect(x: 15, y: 25+lessonLabel.frame.origin.y, width: 270, height: 20))
        clubLabel.font = UIFont.systemFont(ofSize: 16)
        clubLabel.text = "所在俱乐部: 帝壹射箭俱乐部"
        mainScrollView.addSubview(clubLabel)
        
        let timeLabel = UILabel(frame: CGRect(x: 15, y: 25+clubLabel.frame.origin.y, width: 270, height: 20))
        timeLabel.font = UIFont.systemFont(ofSize: 16)
        timeLabel.text = "授课时间: 14:00-20:00"
        mainScrollView.addSubview(timeLabel)
        
        let countLabel = UILabel(frame: CGRect(x: 15, y: 25+timeLabel.frame.origin.y, width: 270, height: 20))
        countLabel.font = UIFont.systemFont(ofSize: 16)
        countLabel.text = "关注人数: \(infoDict.value(forKey: "hits") as! String)人"
        mainScrollView.addSubview(countLabel)
        
        let commentView = UIView(frame: CGRect(x: WIDTH, y: HEIGHT-mainScrollView.frame.origin.y-49, width: WIDTH, height: 49))
        commentView.backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1)
        commentView.layer.shadowPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: WIDTH, height: 2)).cgPath
        commentView.layer.shadowColor = UIColor.gray.cgColor
        commentView.layer.shadowOffset = CGSize(width: 0, height: -1)
        commentView.layer.shadowOpacity = 0.6
        commentView.layer.shadowRadius = 1
        mainScrollView.addSubview(commentView)
        
        field = UITextField(frame: CGRect(x: 10, y: 0, width: WIDTH*0.7, height: 30))
        field.center.y = 49/2
        field.placeholder = "请输入"
        field.backgroundColor = UIColor.white
        field.layer.cornerRadius = 5
        field.layer.masksToBounds = true
        field.font = UIFont.systemFont(ofSize: 16)
        commentView.addSubview(field)
        
        let postBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 54, height: 30))
        postBtn.layer.borderColor = UIColor.lightGray.cgColor
        postBtn.layer.borderWidth = 0.5
        postBtn.layer.cornerRadius = 5
        postBtn.layer.masksToBounds = true
        postBtn.setTitle("提 问", for: .normal)
        postBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        postBtn.setTitleColor(UIColor.brown, for: .normal)
        postBtn.center = CGPoint(x: 0.85*WIDTH, y: 49/2)
        commentView.addSubview(postBtn)
        
        postBtn.addTarget(self, action: #selector(post), for: .touchUpInside)
        
        let focusBtn = CustomButton(frame: CGRect(x: WIDTH-15-100, y: 0, width: 100, height: 40))
        focusBtn.backgroundColor = UIColor.white
        focusBtn.circleColor = UIColor.black
        focusBtn.center.y = navBar.backBtn.center.y
        focusBtn.setTitle("关注", for: .normal)
        focusBtn.setTitleColor(.black, for: .normal)
        focusBtn.adjustsImageWhenDisabled = false
        focusBtn.isEnabled = false
        focusBtn.contentHorizontalAlignment = .right
        focusBtn.animation()
        navBar.addSubview(focusBtn)
        
        tableView = UITableView(frame: CGRect(x: WIDTH, y: 0, width: WIDTH, height: HEIGHT-mainScrollView.frame.origin.y-49))
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.backgroundColor = view.backgroundColor
        mainScrollView.addSubview(tableView)
        
        isExits(button: focusBtn)
        
        focusBtn.addTarget(self, action: #selector(focus), for: .touchUpInside)
        navBar.backBtn.addTarget(self, action: #selector(back), for: .touchUpInside)
        btnView.firstBtn.addTarget(self, action: #selector(onClick), for: .touchUpInside)
        btnView.secondBtn.addTarget(self, action: #selector(onClick), for: .touchUpInside)
        
        videoPlayer.fullBtn.addTarget(self, action: #selector(fullScreen), for: .touchUpInside)
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return chatArray?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
        cell.selectionStyle = .none
        let dict = chatArray![indexPath.row]
        
        cell.textLabel?.text = dict.value(forKey: "content") as? String
        cell.detailTextLabel?.text = dict.value(forKey: "time") as? String
        
        return cell
    }
    
    @objc func post(){
        if chatArray == nil{
            chatArray = []
        }
        let dict:NSMutableDictionary = [:]
        dict.setValue(field.text!, forKey: "content")
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = DateFormatter.Style.full
        dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
        let time = dateFormatter.string(from: Date())
        dict.setValue(time, forKey: "time")
        field.text = ""
        chatArray?.append(dict)
        tableView.reloadData()
    }
    
    @objc func fullScreen(){
        let pw = videoPlayer.bounds.width
        let ph = videoPlayer.bounds.height
        if !hideState{
            UIView.animate(withDuration: 0.3, animations: {
                self.videoPlayer.transform =
                    CGAffineTransform(rotationAngle: CGFloat(Double.pi/180)*CGFloat(90)).concatenating(
                    CGAffineTransform(scaleX: WIDTH/ph,
                                      y: HEIGHT/pw)).concatenating(
                    CGAffineTransform(translationX: 0,
                                      y: -25.833-64-23.334))
            })
            hideState = !hideState
            setNeedsStatusBarAppearanceUpdate()
        }
        else{
            UIView.animate(withDuration: 0.3, animations: {
                self.videoPlayer.transform = .identity
            })
            hideState = !hideState
            setNeedsStatusBarAppearanceUpdate()
        }
    }
    
    @objc func onClick(sender:UIButton){
        let circle = btnView.circle!
        circle.anim.location = sender.center
        switch sender.tag {
        case 1:
            if circle.c2 != circle.c1{
                circle.anim.direction = "left"
                circle.link.isPaused = false
                mainScrollView.setContentOffset(CGPoint(x:0,y:0), animated: true)
            }
        case 2:
            if circle.c2 == circle.c1{
                circle.anim.direction = "right"
                circle.link.isPaused = false
                mainScrollView.setContentOffset(CGPoint(x:WIDTH,y:0), animated: true)
            }
        default:
            break
        }
    }
    
    @objc func focus(sender:UIButton){
        let parameter:NSDictionary = [
            "SessionID" :   LoginModel.sessionID,
            "fan_id"    :   self.infoDict.value(forKey: "id") as! String,
            "fans_type" :   "2",
            "userid"    :   LoginModel.userID
        ]
        if sender.isEnabled{
            let popup = Popup()
            if sender.titleLabel?.text == "关注"{
                Networking.shared.focus_Join(parameter: parameter) {
                    DispatchQueue.main.async {
                        popup.appear(title: "关注成功", action: nil)
                        sender.setTitle("取消关注", for: .normal)
                    }
                }
            }else{
                Networking.shared.delete(parameter: parameter, block: {
                    DispatchQueue.main.async {
                        popup.appear(title: "取消关注成功", action: nil)
                        sender.setTitle("关注", for: .normal)
                    }
                })
            }
        }
    }
    
    func isExits(button:CustomButton){
        let parameters:NSDictionary = [
            "SessionID"     :   LoginModel.sessionID,
            "fan_id"        :   infoDict.value(forKey: "id") as! String,
            "userid"        :   LoginModel.userID,
            "fans_type"     :   "2",
            ]
        Networking.shared.isExits(parameter: parameters) {(success) in
            DispatchQueue.main.async {
                if success{
                    button.setTitle("取消关注", for: .normal)
                }
                button.isEnabled = true
                button.stopAnimation()
            }
        }
    }
    
    override var prefersStatusBarHidden: Bool{
        return hideState
    }
    
    @objc func back(){
        videoPlayer.disAppear()
        _ = navigationController?.popViewController(animated: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
